package com.bigData.main.controller;

import com.bigData.main.TestSocket.TestClient;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/api/client")
public class ClientController {

    @PostMapping("/verify")
    public ResponseEntity<?> verifyClient(@RequestBody Map<String, String> request) {
        String ip = request.get("ip");
        String code = request.get("code");

        try {
            if (!TestClient.pingServer(ip)) {
                return ResponseEntity.status(500).body("无法连接服务器");
            }

            String result = TestClient.verifyCode(code, ip);
            return ResponseEntity.ok().contentType(MediaType.TEXT_PLAIN).body(result);
        } catch (IOException e) {
            return ResponseEntity.status(500).body("通信错误: " + e.getMessage());
        }
    }

    // 新增会话验证接口
    @GetMapping("/verify")
    public ResponseEntity<?> checkSession(
            @RequestParam String ip,
            @RequestParam String code
    ) {
        try {
            if (!TestClient.pingServer(ip)) {
                return ResponseEntity.status(500).body("connection_failed");
            }

            String result = TestClient.verifyCode(code, ip);
            return ResponseEntity.ok().contentType(MediaType.TEXT_PLAIN).body(result);
        } catch (IOException e) {
            return ResponseEntity.status(500).body("communication_error");
        }
    }
}